package com.reagent;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.junit.jupiter.api.Test;

import java.util.Calendar;
import java.util.HashMap;

public class ReagentApp {

    //获取令牌
    @Test
    void getToken() {
        HashMap<String, Object> map = new HashMap<>();
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.SECOND, 60);  //设置过期时间
        //创建JWT
        String token = JWT.create()
                .withHeader(map)  //Header(可以省略不写)
                .withClaim("userId", 21)  //Payload(不要存放敏感信息，类似于session)
                .withClaim("username", "admin")
                .withExpiresAt(instance.getTime())  //指定令牌过期时间
                .sign(Algorithm.HMAC256("!Q@W#E$R"));//签名(指定密钥)
        System.out.println("token = " + token);
    }

    //令牌验证
    @Test
    void authoToken() {
        /*
        * 1.先验证签名
        * 2.在做解码
        * 3.在做过期异常
        * */
        //注意：验证(即解密)时的算法要与生成时一致，否者无法验证
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256("!Q@W#E$R")).build();
        DecodedJWT verify = jwtVerifier.verify("eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MDYwNjgzNDMsInVzZXJJZCI6MjEsInVzZXJuYW1lIjoiYWRtaW4ifQ.ZDsFNMGi-QrFaMF5x3F80EpvKNtJMXRbI_B3nmmNaec");

        System.out.println("过期时间:" + verify.getExpiresAt());
        System.out.println(verify.getClaim("userId").asInt());
        System.out.println(verify.getClaim("username").asString());
    }

    @Test
    void testLogin() {

    }

}
